package TCP.TCP8;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

public class TcpClient {

    private Socket clientSocket;

    public TcpClient(String serverIp, int port) throws IOException {
        this.clientSocket = new Socket(serverIp, port);
    }

    public void start() {
        try(InputStream inputStream = clientSocket.getInputStream();
            OutputStream outputStream = clientSocket.getOutputStream()) {
            Scanner input = new Scanner(System.in);
            PrintWriter outputSocket = new PrintWriter(outputStream);
            Scanner inputSocket = new Scanner(inputStream);
            while(true) {
                //1.输入请求
                System.out.print("->");
                String request = input.next();
                //2.发送请求给服务器
                outputSocket.println(request);
                outputSocket.flush();
                //3.接收服务器响应
                String response = inputSocket.next();
                //4.打印响应
                System.out.println(response);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws IOException {
        TcpClient tcpClient = new TcpClient("127.0.0.1", 8080);
        tcpClient.start();
    }

}
